/*******************************************************************************
 * Package: com.song.boot.springstudy.netty.ws
 * Type:    WebSocketServerHandler
 * Date:    2023-06-24 17:41
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.netty.websocket.ws;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDate;

/**
 * 功能描述： 处理器
 *
 * @author Songxianyang
 * @date 2023-06-24 17:41
 */
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println("获取客户端发送过来的消息为》》》》》》》》》》》："+textWebSocketFrame.text()+"<<<<<<<<<<<<<");
        // 自动回复客户端信息   时间加信息
        channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame(LocalDate.now() + textWebSocketFrame.text()+"<><>自动回复客户端信息"));
    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        ChannelPipeline pipeline = ctx.pipeline();
        System.out.println("获取浏览器中的通道channel>>>>>>>>:"+pipeline.channel().id().asLongText());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("关闭了浏览器中的通道channel>>>>>>>>:"+channel.id().asLongText());
    }
    // 发生异常，则关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("发生异常关闭通道");
        ctx.close();
    }
}
